package com.heima.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mrchen
 * @date 2021/12/30 10:40
 */
@Component
@Slf4j
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    // 初始化白名单 url路径
    static {
        // 登录
        urlList.add("/login/in");
        // 接口文档路径
        urlList.add("/v2/api-docs");
    }


    /**
     * @param exchange 封装 了 请求 和 响应
     * @param chain  过滤器lian
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 1. 判断请求是否是白名单路径
        // /admin/login/in
        String path = request.getURI().getPath();
        for (String allowUri : urlList) {
            if(path.contains(allowUri)){
                // 2.  如果是 直接放行
                return chain.filter(exchange);
            }
        }
        // 3.  获取请求头中的token信息
        String token = request.getHeaders().getFirst("token");
        // 3.1   如果token不存在  直接返回401 未登录
        if(StringUtils.isBlank(token)){
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            // 直接终止请求
//            return response.setComplete();
            return writeMessage(exchange,"未发现 token");
        }
        // 4.  基于jwt工具类 解析token
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            // -1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i < 1){
                // 4.1  解析成功   获取token中的userId
                Object id = claimsBody.get("id");
                // 4.2  将userId重新设置到请求头中
                request = request.mutate().header("userId", String.valueOf(id)).build();
                exchange = exchange.mutate().request(request).build();
                log.info("token 校验成功 当前userId = {}",id);
                // 4.3  放行请求
                return chain.filter(exchange);
            }else {
                log.error("token已经失效");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("网关校验token 失败 {}",e.getMessage());
        }
        // 5. 如果解析失败  直接返回401 未登录
//        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 直接终止请求
//        return response.setComplete();
        return writeMessage(exchange,"网关校验token 失败");
    }

    /**
     * 返回错误提示信息
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}